<template>
  <div>
    <p>
      <!--  刷新按钮  -->
      <button class="btn btn-white btn-default btn-round" @click="list(1)">
        <i class="ace-icon fa fa-refresh"></i>
        刷新
      </button> &nbsp;

      <!--  新增按钮  -->
      <button class="btn btn-white btn-default btn-round" @click="add()">
        <i class="ace-icon fa fa-edit"></i>
        新增
      </button> &nbsp;
    </p>

    <!--  增加分页组件  -->
    <pagination ref="pagination" v-bind:list="list"></pagination>


    <div class="row">
      <div class="col-md-4" v-for="course in courses">
        <!--  课程管理的展示封面  -->
        <div class="thumbnail search-thumbnail">
          <!--  如果课程没有图片就默认使用这张图片  -->
          <img v-show="!course.image" class="media-object" src="/static/image/test-course.jpg"/>
          <!--  如果课程上传了图片就显示上传的图片  -->
          <img v-show="course.image" class="media-object" v-bind:src="course.image"/>

          <!--  显示课程的枚举字段信息  -->
          <div class="caption">
            <div class="clearfix">
              <span class="pull-right label label-danger info-label">
                {{ COURSE_LEVEL | optionKV(course.level) }}
              </span>
              <span class="pull-right label label-primary info-label">
                {{ COURSE_CHARGE | optionKV(course.charge) }}
              </span>
              <span class="pull-right label label-success info-label">
                {{ COURSE_STATUS | optionKV(course.status) }}
              </span>
            </div>

            <!--  课程名称  -->
            <h3 class="search-title">
              <span class="blue">{{ course.name }}</span>
            </h3>

            <!--  讲师信息显示  -->
            <!--  v-for中，对循环数组，可以通过filter来进行过滤  -->
            <div v-for="teacher in teachers.filter(t => {return t.id === course.teacherId})" class="profile-activity clearfix">
              <div>
                <img v-show="!teacher.image" class="pull-left" src="/static/image/header2.jpg"/>
                <img v-show="teacher.image" class="pull-left" v-bind:src="teacher.image"/>
                <a class="user" href="#">{{ teacher.name }}</a>
                <br>
                {{ teacher.position }}
              </div>
            </div>

            <!--  课程价格  -->
            <p>
              <span class="blue bolder bigger-150">
                <i class="fa fa-rmb"></i>
                {{ course.price }}&nbsp;
              </span>
            </p>

            <!--  课程描述  -->
            <p>{{ course.summary }}</p>

            <!--  课程信息的基本操作  -->
            <p>
              <span class="badge badge-info">{{ course.id }}</span>
              <span class="badge badge-info">排序：{{ course.sort }}</span>
              <span class="badge badge-info">时长：{{ course.time | formatSecond }}</span>
            </p>

            <!--  课程操作  -->
            <p>
              <!--  对应大章按钮  -->
              <button class="btn btn-white btn-xs btn-info btn-round" @click="toChapter(course)">
                <i class="ace-icon fa fa-list bigger-160"></i>
                章节
              </button>&nbsp;

              <button class="btn btn-white btn-xs btn-warning btn-round" @click="toContent(course)">
                <i class="ace-icon fa fa-file-code-o bigger-160"></i>
                内容
              </button>&nbsp;

              <button class="btn btn-white btn-xs btn-primary btn-round" @click="openSortModal(course)">
                <i class="ace-icon fa fa-sort-numeric-asc bigger-160"></i>
                排序
              </button>&nbsp;

              <button class="btn btn-white btn-xs btn-success btn-round" @click="edit(course)">
                <i class="ace-icon fa fa-pencil bigger-160"></i>
                编辑
              </button>&nbsp;

              <button class="btn btn-white btn-xs btn-danger btn-round" @click="del(course.id)">
                <i class="ace-icon fa fa-trash-o bigger-160"></i>
                删除
              </button>
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- PAGE CONTENT BEGINS -->

    <!--  模态框  -->
    <div id="form-modal" class="modal fade" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title">课程信息</h4>
          </div>
          <!--  模态框主体内容  -->
          <div class="modal-body">

            <!--  模态框中的表单  -->
            <form class="form-horizontal">
              <!--  引入zTree jQuery组件  -->
              <div class="form-group">
                <!--  定义zTree的标题  -->
                <label class="col-sm-2 control-label">
                  分类
                </label>
                <!--  定义zTree的身体  -->
                <div class="col-sm-10">
                  <ul id="tree" class="ztree"></ul>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">封面</label>
                <div class="col-sm-10">
                  <big-file v-bind:input-id="'image-upload'"
                        v-bind:text="'上传封面'"
                        v-bind:use="FILE_USE.COURSE.key"
                        v-bind:suffixs="['jpg', 'jpeg', 'png']"
                        v-bind:after-upload="afterUpload"></big-file>
                  <div v-show="course.image" class="row"><br>
                    <div class="col-md-6">
                      <img v-bind:src="course.image" class="img-responsive"/>
                    </div>
                  </div>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">名称</label>
                <div class="col-sm-10">
                  <input type="text" v-model="course.name" class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">概述</label>
                <div class="col-sm-10">
                  <textarea type="text" v-model="course.summary" class="form-control" rows="3"/>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">讲师 </label>
                <div class="col-sm-10">
                  <select v-model="course.teacherId" class="form-control">
                    <option v-for="o in teachers" v-bind:value="o.id">{{ o.name }}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">时长</label>
                <div class="col-sm-10">
                  <input type="text" v-model="course.time" class="form-control" disabled>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">价格(元)</label>
                <div class="col-sm-10">
                  <input type="text" v-model="course.price" class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">级别 </label>
                <div class="col-sm-10">
                  <select v-model="course.level" class="form-control">
                    <option v-for="o in COURSE_LEVEL" v-bind:value="o.key">{{ o.value }}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">收费 </label>
                <div class="col-sm-10">
                  <select v-model="course.charge" class="form-control">
                    <option v-for="o in COURSE_CHARGE" v-bind:value="o.key">{{ o.value }}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">状态 </label>
                <div class="col-sm-10">
                  <select v-model="course.status" class="form-control">
                    <option v-for="o in COURSE_STATUS" v-bind:value="o.key">{{ o.value }}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">报名数</label>
                <div class="col-sm-10">
                  <input type="text" v-model="course.enroll" class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">顺序</label>
                <div class="col-sm-10">
                  <input type="text" v-model="course.sort" class="form-control" disabled/>
                </div>
              </div>
            </form>
          </div>

          <!--  模态框底部内容  -->
          <div class="modal-footer">
            <!--  data-dismiss的作用为关闭模态框的事件  -->
            <button type="button" class="btn btn-white btn-lg btn-danger btn-round" data-dismiss="modal">
              <i class="ace-icon fa fa-times red"></i>
              取消
            </button>
            <button type="button" class="btn btn-white btn-lg btn-info btn-round" @click="save()">
              <i class="ace-icon fa fa-save blue"></i>
              保存
            </button>
          </div>

        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

    <!--  排序模态框  -->
    <div id="course-sort-modal" class="modal fade" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title">修改排序</h4>
          </div>
          <!--  模态框主体内容  -->
          <div class="modal-body">

            <!--  模态框中的表单  -->
            <form class="form-horizontal">

              <div class="form-group">
                <label class="control-label col-lg-3">
                  当前排序
                </label>
                <div class="col-lg-9">
                  <input class="form-control" v-model="sort.oldSort" name="oldSort" disabled/>
                </div>
              </div>

              <div class="form-group">
                <label class="control-label col-lg-3">
                  新的排序
                </label>
                <div class="col-lg-9">
                  <input class="form-control" v-model="sort.newSort" name="newSort"/>
                </div>
              </div>
            </form>
          </div>

          <!--  模态框底部内容  -->
          <div class="modal-footer">
            <!--  data-dismiss的作用为关闭模态框的事件  -->
            <button type="button" class="btn btn-white btn-lg btn-danger btn-round" data-dismiss="modal">
              <i class="ace-icon fa fa-times red"></i>
              取消
            </button>
            <button type="button" class="btn btn-white btn-lg btn-info btn-round" @click="updateSort()">
              <i class="ace-icon fa fa-save blue"></i>
              更新排序
            </button>
          </div>

        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->


    <!-- PAGE CONTENT ENDS -->

  </div>

</template>

<script>
import Pagination from "../../components/pagination"
import BigFile from "../../components/big-file"

export default {
  name: "business-course",
  components: {Pagination, BigFile},
  mounted: function () {
    let _this = this;
    _this.list(1);
    // 初始化每页显示10条数据
    _this.$refs.pagination.size = 10;
    // 初始化zTree
    _this.allCategory();
    // 初始加载所有讲师
    _this.allTeacher();

    // 将左侧栏的样式激活
    // this.$parent.activeSidebar("business-course-sidebar");
  },
  data: function () {
    return {
      // 用来映射表单的数据
      course: {},
      courses: [],
      COURSE_LEVEL: COURSE_LEVEL,
      COURSE_CHARGE: COURSE_CHARGE,
      COURSE_STATUS: COURSE_STATUS,
      FILE_USE: FILE_USE,
      categorys: [],
      tree: {},
      saveContentLabel: "",
      sort: {
        id: "",
        oldSort: 0,
        newSort: 0
      },
      // 加载数据库中所有的讲师
      teachers: [],
      files: [],
    }
  },
  methods: {
    list(page) {
      let _this = this;
      // 调用显示延迟框的方法
      Loading.show();
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/course/list', {
        page: page,
        size: _this.$refs.pagination.size
      }).then((result) => {
        // 关闭延迟框的显示
        Loading.hide();
        let response = result.data;
        _this.courses = response.content.list;
        _this.$refs.pagination.render(page, response.content.total);
      })
    },

    // 当点击新增按钮时触发的事件
    add() {
      let _this = this;
      _this.course = {
        // 令新增排序的数字为当前分页的总条数+1
        sort: _this.$refs.pagination.total + 1
      };
      // 点击新增时让所有的节点都不选中
      _this.tree.checkAllNodes(false);
      $("#form-modal").modal("show");
    },

    // 当点击编辑按钮时触发的事件
    edit(course) {
      let _this = this;
      _this.course = $.extend({}, course);
      // 查找当前课程勾选的分类
      _this.listCategory(course.id);
      $("#form-modal").modal("show");
    },

    // 编辑和新增的调用方法
    save(page) {
      let _this = this;

      // 保存校验，加1!=1是为了解决第一个||符号的问题
      if (1 != 1
          || !Validator.require(_this.course.name, "名称")
          || !Validator.length(_this.course.name, "名称", 1, 50)
          || !Validator.length(_this.course.summary, "概述", 1, 2000)
          || !Validator.length(_this.course.image, "封面", 1, 100)
      ) {
        return;
      }

      // 获取选择的所有分类
      let categorys = _this.tree.getCheckedNodes();
      // 判断课程是否选择了分类
      if (Tool.isEmpty(categorys)) {
        Toast.warning("请选择分类！");
        return;
      }
      // 将选择的分类做为course对象的属性传递到后台
      _this.course.categorys = categorys;

      // 调用显示延迟框的方法
      Loading.show();
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/course/save', _this.course).then((result) => {
        // 关闭延迟框的显示
        Loading.hide();
        // 用response来代替result.data
        let response = result.data;
        if (response.success) {
          $("#form-modal").modal("hide");
          _this.list(1);
          Toast.success("编辑成功！")
        } else {
          Toast.warning(response.message)
        }
      })
    },

    // 删除的调用方法
    del(id) {
      let _this = this;
      Confirm.show("删除后不可恢复，确认删除吗？", function () {
        // 调用显示延迟框的方法
        Loading.show();
        _this.$ajax.delete(process.env.VUE_APP_SERVER + '/business/admin/course/delete/' + id).then((result) => {
          let response = result.data;
          // 当删除成功时
          if (response.success) {
            // 刷新列表
            _this.list(1);
            // 调用Toast组件的成功效果
            Toast.success("删除成功！")
          } // end if

        }) // end then
      })
    },

    // 跳转大章按钮使用的方法，当点击大章按钮后触发的事件
    toChapter(course) {
      let _this = this;
      // 调用自己写好的工具类进行将course对象进行缓存
      SessionStorage.set(SESSION_KEY_COURSE, course);
      // 跳转到大章页面
      _this.$router.push("/business/chapter");
    },

    // 跳转内容按钮使用的方法，当点击内容按钮后触发的事件
    toContent(course) {
      let _this = this;
      // 调用自己写好的工具类进行将course对象进行缓存
      SessionStorage.set(SESSION_KEY_COURSE, course);
      // 跳转到大章页面
      _this.$router.push("/business/content");
    },

    // 初始化zTree
    initTree: function () {
      let _this = this;
      let setting = {
        check: {
          enable: true
        },
        data: {
          simpleData: {
            // 增加Id配置映射
            idKey: "id", // id对应的字段
            pIdKey: "parent", // 父Id对应的字段
            rootPId: "00000000", // 默认父Id为空时的数据
            enable: true
          }
        }
      };

      let zNodes = _this.categorys;
      // 获取到选中的数据并赋值给tree
      _this.tree = $.fn.zTree.init($("#tree"), setting, zNodes);

      // 展开所有节点
      // _this.tree.expandAll(true);
    },

    // 查询所有列表方法
    allCategory() {
      let _this = this;
      // 调用显示延迟框的方法
      Loading.show();
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/category/all').then((result) => {
        // 关闭延迟框的显示
        Loading.hide();
        let response = result.data;
        _this.categorys = response.content;
        _this.initTree();
      })
    },

    /**
     * 查找当前课程下的所有分类
     *
     * @param courseId 课程ID
     */
    listCategory(courseId) {
      let _this = this;
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/course/list-category/' + courseId).then((result) => {
        console.log("查找课程下所有分类结果：", result);
        let response = result.data;
        let categorys = response.content;

        // 勾选查询到的分类
        // 先将所有的树的节点都取消勾选
        _this.tree.checkAllNodes(false);
        for (let i = 0; i < categorys.length; i++) {
          // 查询当前节点
          let node = _this.tree.getNodeByParam("id", categorys[i].categoryId);
          // 勾选当前查询到的节点
          _this.tree.checkNode(node, true);
        }
      })
    },
    // 点击排序按钮时触发的事件
    openSortModal(course) {
      let _this = this;
      // 初始化排序的数据
      _this.sort = {
        id: course.id,
        oldSort: course.sort,
        newSort: course.sort
      }
      // 显示模态框
      $("#course-sort-modal").modal("show");
    },
    // 更新排序的方法
    updateSort() {
      let _this = this;
      if (_this.sort.newSort === this.sort.oldSort) {
        Toast.warning("排序没有变化！");
        return;
      }
      _this.$ajax.post(process.env.VUE_APP_SERVER + "/business/admin/course/sort", _this.sort).then((result) => {
        let response = result.data;
        // 如果返回的状态为成功
        if (response.success) {
          Toast.success("排序更新成功！");
          // 将模态框进行隐藏
          $("#course-sort-modal").modal("hide");
          _this.list(1);
        } else {
          Toast.error("排序更新失败");
        }
      });
    },

    // 查询所有讲师方法
    allTeacher() {
      let _this = this;
      // 调用显示延迟框的方法
      Loading.show();
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/teacher/all').then((result) => {
        // 关闭延迟框的显示
        Loading.hide();
        let response = result.data;
        _this.teachers = response.content;
      })
    },

    afterUpload(response) {
      let _this = this;
      _this.course.image = response.content.path;
    },

  } // methods
};
</script>

<!-- scoped的作用表示当前style中的属性只应用于当前组件  -->
<style scoped>
.caption h3 {
  font-size: 20px;
}

/*  字体大小自适应，通过屏幕的分辨率显示不同大小的字体  */
@media (max-width: 1199px) {
  .caption h3 {
    font-size: 16px;
  }
}
</style>
